package service

import (
	"context"
	"fmt"

	model "gitee.com/hust-ideas/little-genius-backend/model"
	"gitee.com/hust-ideas/little-genius-backend/proto"
)

func (s *ServiceContext) KeywordGen(req model.KeywordsKeywordIdGenerateQuestionPostReq, c context.Context) (model.KeywordsKeywordIdGenerateQuestionPostResp, error) {
	keyword, err := s.Model.KeywordsModel.FindOne(c, req.KeywordId)
	// 验证关键词是否存在
	if err != nil {
		return model.KeywordsKeywordIdGenerateQuestionPostResp{}, err
	}
	// 验证用户 id 是否和关键词用户 id 一致
	if keyword.KUId != uint64(req.UserId) {
		return model.KeywordsKeywordIdGenerateQuestionPostResp{}, model.ErrNoPermission
	}
	fmt.Println(req.Quantity)
	// 调用题目生成 RPC 服务
	reqRPC := &proto.GetQuestionsRequest{
		Keyword: &proto.Keyword{
			Grade:      keyword.KGrade,
			Subject:    keyword.KSubject,
			Difficulty: keyword.KDifficulty,
			Topic:      keyword.KName,
		},
		Quantity: int32(req.Quantity),
	}
	// 调用 RPC 服务
	resRPC, err := s.CallQuestionGenService(reqRPC)
	if err != nil {
		return model.KeywordsKeywordIdGenerateQuestionPostResp{}, err
	}
	// 将 RPC 服务返回的题目转换为 model.Question
	var questions []model.Question
	for _, question := range resRPC.Questions {
		questions = append(questions, model.Question{
			Description: question.QuestionText,
			Answer:      question.Answer,
		})
	}
	return model.KeywordsKeywordIdGenerateQuestionPostResp{
		Questions: questions,
	}, nil
}
